#!/usr/bin/env python3

import subprocess
import os
import time
import getopt
import sys

output = "dist\\"
cam_path = '/sdcard/DCIM/Camera/'


def run_cmd(cmd):
    result = subprocess.run(cmd,
                            stdout=subprocess.PIPE)
    return result.returncode, result.stdout.decode()


def main():
    adb = f"adb"
    optlist, args = getopt.getopt(sys.argv[1:], 's:')
    device_id = [v for k, v in optlist if k == '-s']
    assert len(device_id) <= 1
    if len(device_id) == 1:
        adb = f"adb -s {device_id[0]}"
    adb_shell = f"{adb} shell"
    code, _ = run_cmd(f"{adb_shell} find {cam_path} -type f")
    assert code == 0, "命令失败"

    output_path = os.path.abspath(output) + os.path.sep
    print(f"{cam_path} => {output_path}")
    os.makedirs(output_path, exist_ok=True)

    run_cmd(f"{adb_shell} input keyevent KEYCODE_CAMERA")
    # 获取最近10s文件
    for _ in range(10):
        code, r = run_cmd(f"{adb_shell} find {cam_path} -type f -ctime -30s")
        file = [None, *r.splitlines()][-1]
        if file is not None:
            break
        time.sleep(0.1)
    assert file is not None, "没有找到照片"
    run_cmd(f"{adb} pull {file} {output_path}")
    print(f"remove {file}")
    run_cmd(f"{adb_shell} rm -v {file}")


if __name__ == "__main__":
    main()
